﻿Option Explicit On

Imports System.Xml

Public Class frmFerramentasWebServices

    Private Sub frmFerramentasWebServices_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With cmbNFeTpAmb
            .Clear()
            .Add("HOMOLOGAÇÃO", "2")
            .Add("PRODUÇÃO", "1")
        End With
        With cmbNFeUF
            .Clear()
            .SQL = "SELECT descricao, cod_uf FROM ufs ORDER BY descricao ASC"
            .Reload()
        End With
        With cmbNFeServico
            .Clear()
            .Add("Inutilização de Numeração de NFe [NfeInutilizacao]", "NfeInutilizacao")
            .Add("Envio de Lote de NFe [NfeRecepcao]", "NfeRecepcao")
            .Add("Consulta Cadastro Contribuites [ConsultaCadastro]", "ConsultaCadastro")
            .Add("Cancelamento de NFe [NfeCancelamento]", "NfeCancelamento")
            .Add("Consulta de NFe Pela Chave [NfeConsultaNF]", "NfeConsultaNF")
            .Add("Consulta de Recibo de Envio de Lote de NFe [NfeRetRecepcao]", "NfeRetRecepcao")
            .Add("Consulta de Status do Serviço [NfeStatusServico]", "NfeStatusServico")
            .Add("Envio de Lote de Carta de Correção Eletrônica [NfeRecepcaoEvento]", "NfeRecepcaoEvento")
        End With
        Call MontaGrid()
        Call Cancelar()
    End Sub

    Private Sub MontaGrid()
        With dgvResult
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .ConnectionString = strMyDBString
            .TypeConnection = AnguloGridView.EnumTypeConection.SQLiteDataAdapter
            .SQL = "SELECT a.cod_uf, b.descricao, a.tp_amb, a.servico, a.url " & _
                   "FROM webservices a " & _
                   "LEFT JOIN ufs b ON b.cod_uf = a.cod_uf "
            .AddColumn("cod_uf", 10, False)
            .AddColumn("UF", 75)
            .AddColumn("Ambiente [1=Produção/2=Homologação]", 25)
            .AddColumn("Serviço", 100)
            .AddColumn("URL", 0)
        End With
    End Sub

    Private Sub tbGridSimples_ItemClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles tbGridSimples.ItemClicked
        Select Case e.ClickedItem.Tag
            Case "CA"
                Call Cancelar()
            Case "IN"
                Call Inserir()
            Case "GR"
                Call Gravar()
            Case "ED"
                Call Editar()
            Case "EX"
                Call Excluir()
            Case "IDX"
                Call ImportarWS()
        End Select
    End Sub

    Private Sub GravarDados()
        Try
            mySQLite.Query("SELECT * " & _
                                   "FROM webservices " & _
                                   "WHERE cod_uf='" & cmbNFeUF.Value & "' " & _
                                   "AND tp_amb=" & cmbNFeTpAmb.Value & " " & _
                                   "AND servico='" & cmbNFeServico.Value & "' ")
            If mySQLite.EOF Then
                mySQLite.AddNew()
                mySQLite.Field("cod_uf") = cmbNFeUF.Value
                mySQLite.Field("tp_amb") = cmbNFeTpAmb.Value
                mySQLite.Field("servico") = cmbNFeServico.Value
            End If
            mySQLite.Field("url") = TrataNull(txtURL.Text, TypeCode.String)
            mySQLite.Update()
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub Inserir()
        tbGridSimples.ToolOrder("IN")
        gpbDados.Enabled = True
        cmbNFeUF.Enabled = True
        cmbNFeTpAmb.Enabled = True
        cmbNFeServico.Enabled = True
        cmbNFeUF.Focus()
    End Sub

    Private Sub Gravar()
        If cmbNFeTpAmb.Value.ToString.Trim = String.Empty Then
            Call MsgBox("Selecione o tipo de ambiente!", MsgBoxStyle.Exclamation)
            cmbNFeTpAmb.Select()
            Exit Sub
        End If
        If cmbNFeUF.Value.ToString.Trim = String.Empty Then
            Call MsgBox("Selecione uma UF ou SCAN!", MsgBoxStyle.Exclamation)
            cmbNFeUF.Select()
            Exit Sub
        End If
        If cmbNFeServico.Value.ToString.Trim = String.Empty Then
            Call MsgBox("Selecione um serviço!", MsgBoxStyle.Exclamation)
            cmbNFeServico.Select()
            Exit Sub
        End If
        If txtURL.Text.ToString.Trim = String.Empty Then
            Call MsgBox("Digite uma URL para o WebService válida!", MsgBoxStyle.Exclamation)
            txtURL.Select()
            Exit Sub
        End If
        Call GravarDados()
        Call Cancelar()
    End Sub

    Private Sub Cancelar()
        Call LimpaForm(Me)
        tbGridSimples.ToolOrder("CA")
        dgvResult.Reload()
        gpbDados.Enabled = False
    End Sub

    Private Sub Editar()
        Try
            Dim strVariavel As String = dgvResult.CurrentRowCel("nome")
            With dgvResult
                mySQLite.Query("SELECT * " & _
                         "FROM webservices " & _
                         "WHERE cod_uf='" & .CurrentRowCel("cod_uf") & "' " & _
                         "AND tp_amb=" & .CurrentRowCel("tp_amb") & " " & _
                         "AND servico='" & .CurrentRowCel("servico") & "' ")
            End With

            If Not mySQLite.EOF Then
                cmbNFeUF.Buscar = TrataNull(mySQLite.Field("cod_uf"), TypeCode.String)
                cmbNFeTpAmb.Buscar = TrataNull(mySQLite.Field("tp_amb"), TypeCode.Int16)
                cmbNFeServico.Buscar = TrataNull(mySQLite.Field("servico"), TypeCode.String)
                txtURL.Text = TrataNull(mySQLite.Field("url"), TypeCode.String)
                '--
                tbGridSimples.ToolOrder("ED")
                gpbDados.Enabled = True
                cmbNFeUF.Enabled = False
                cmbNFeTpAmb.Enabled = False
                cmbNFeServico.Enabled = False
                txtURL.Select()
            Else
                Call MsgBox("WebService não consta na base de dados!", MsgBoxStyle.Exclamation)
            End If
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub Excluir()
        If MsgBox("Deseja realmente excluir este WebService?", MsgBoxStyle.Question & MsgBoxStyle.YesNo) = MsgBoxResult.No Then Exit Sub
        Try
            mySQLite.Execute("DELETE FROM webservices " & _
                                   "WHERE cod_uf='" & cmbNFeUF.Value & "' " & _
                                   "AND tp_amb=" & cmbNFeTpAmb.Value & " " & _
                                   "AND servico='" & cmbNFeServico.Value & "' ")
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        Finally
            Call Cancelar()
            tbGridSimples.ToolOrder("EX")
        End Try
    End Sub

    Private Sub ImportarWS()
        Try
            Dim AbrirComo As OpenFileDialog = New OpenFileDialog()
            Dim caminho As DialogResult

            With AbrirComo
                .Title = "Importar WebServices"
                .FileName = ""
                .Filter = "XML eXtensible Markup Language (*.xml)|*.xml"
                caminho = .ShowDialog
                If .FileName.ToString.Trim <> String.Empty Then
                    If IO.File.Exists(.FileName.ToString.Trim) Then
                        Call InserirWS(.FileName.ToString.Trim)
                    End If
                End If
            End With
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub InserirWS(ByVal Filepath As String)
        Try
            Dim myXML As New XmlDocument()
            Dim myXMLString As String = ""
            Dim strUF, strServico, strURL As String
            Dim intAmb As Int16
            Dim strSQL As String = ""
            If ValidaSchema("ImpWebservices", Filepath, myXMLString) = False Then
                Exit Sub
            End If
            With myXML
                .LoadXml(myXMLString)

                For intGroupNode As Integer = 0 To .SelectNodes("/webservices/grupo").Count - 1
                    For intWsNode As Integer = 0 To .SelectNodes("/webservices/grupo[" & intGroupNode + 1 & "]/ws").Count - 1
                        strUF = .SelectNodes("/webservices/grupo[" & intGroupNode + 1 & "]/ws").Item(intWsNode).Attributes("cod_uf").InnerText
                        intAmb = .SelectNodes("/webservices/grupo[" & intGroupNode + 1 & "]/ws").Item(intWsNode).Attributes("tp_amb").InnerText
                        strServico = .SelectNodes("/webservices/grupo[" & intGroupNode + 1 & "]/ws").Item(intWsNode).Attributes("servico").InnerText
                        strURL = .SelectNodes("/webservices/grupo[" & intGroupNode + 1 & "]/ws").Item(intWsNode).Attributes("url").InnerText
                        '--
                        mySQLite.Query("SELECT url " & _
                                       "FROM webservices " & _
                                       "WHERE cod_uf='" & strUF.Trim & "' " & _
                                       "AND tp_amb=" & intAmb & " " & _
                                       "AND servico='" & strServico.Trim & "'")
                        If mySQLite.EOF Then
                            mySQLite.Execute("INSERT INTO webservices(cod_uf, tp_amb, servico, url) " & _
                                             "VALUES('" & strUF.Trim & "'," & intAmb & ",'" & strServico.Trim & "','" & strURL.Trim & "')")
                        End If
                    Next
                Next
            End With
            dgvResult.Reload()
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        Finally

        End Try
    End Sub

End Class